<template>
    <div class="read-progress-container">
        <span
            class="read-progress-bar"
            :class="{ 'with-shadow': shadow }"
            :style="{
                width: readProgress + '%',
                color: color,
                height: height,
                opacity: opacity,
                backgroundColor: color
            }"
        ></span>
    </div>
</template>

<script lang="ts" setup>
import { ref, Ref, onBeforeUnmount } from 'vue';

const readProgress: Ref<number> = ref(0);

defineProps({
    color: {
        type: String,
        default: '#506888'
    },
    height: {
        type: String,
        default: '4px'
    },
    opacity: {
        type: [String, Number],
        default: 1
    },
    shadow: {
        type: Boolean,
        default: true
    }
});
//更新阅读条的状态
const updateReadProgress = (): void => {
    readProgress.value = currentScrollPosition(window.scrollY);
};
//滚轮触发事件
const currentScrollPosition = (position: number): number => {
    const change: number =
        position / (document.body.clientHeight - document.documentElement.clientHeight);
    return change * 100;
};
//监听滚轮事件
window.addEventListener('scroll', updateReadProgress);

//移除滚轮监听函数
onBeforeUnmount(() => {
    window.removeEventListener('scroll', updateReadProgress);
});
</script>

<style scoped lang="scss">
.read-progress-container {
    width: 100%;
    background-color: transparent;
    position: fixed;
    display: block;
    z-index: 9999;
    top: 0;
    left: 0;
    .read-progress-bar {
        display: block;
        width: 0%;
        height: inherit;
        &.with-shadow {
            box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.3);
        }
    }
}
</style>
